/**
 *  GTUG Zaragoza
 *  http://zaragoza.gtugs.org/
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.gtugs.zaragoza.feeds;

import java.text.DateFormat;
import java.util.TimeZone;

import org.gtugs.zaragoza.R;
import org.gtugs.zaragoza.feeds.provider.FeedEntryContentProvider;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.SimpleCursorAdapter.ViewBinder;

/**
 * 
 * @author francho
 * 
 */
public class FeedsListActivity extends ListActivity implements ViewBinder {

	private MyLoadFeeds mLoadTask;
	private long mNow;

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_PROGRESS);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.feeds_list);

		super.onCreate(savedInstanceState);

		setupAdapter();

	}

	@Override
	protected void onResume() {
		Time time = new Time();
		time.setToNow();
		time.switchTimezone(Time.TIMEZONE_UTC);
		mNow = time.toMillis(true);
		super.onResume();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		Intent feedActivity = new Intent(this, FeedActivity.class);
		feedActivity.putExtra(FeedActivity.FEED_ID, id);
		startActivity(feedActivity);
	}

	/**
	 * se llama cada vez que la activity viene a pimer plano y es mostrada al
	 * usuario
	 */
	@Override
	protected void onStart() {
		super.onStart();

		// Carga los datos en segundo plano
		mLoadTask = new MyLoadFeeds();
		mLoadTask.execute();
	}

	/**
	 * La actividad pasa a un segundo plano
	 */
	@Override
	protected void onStop() {

		// Cancelamos la carga si todav�a est� corriendo
		if (mLoadTask != null) {
			mLoadTask.cancel(true);
		}

		super.onStop();
	}

	/**
	 * Asocia los datos al listado
	 * 
	 * @param data
	 */
	void setupAdapter() {
		Cursor cursor = managedQuery(FeedEntryContentProvider.CONTENT_URI_BASE,
				null, null, null, null);

		// Nombre de las campos a mostrar
		String[] from = new String[] { FeedEntry.TITLE, FeedEntry.AUTHOR_NAME,
				FeedEntry.UPDATED };
		// Nombre de los objeto View donde se mostrar�n (corresponden con los
		// de arriba)
		int[] to = new int[] { R.id.itemTitle, R.id.itemAuthor, R.id.itemDate };

		SimpleCursorAdapter adapter = new SimpleCursorAdapter(
				FeedsListActivity.this, // Contexto
				R.layout.feeds_list_item, // Layout a usar en cada fila
				cursor, from, // Ids de objetos View del layout de fila
				to // claves correspondientes
		);

		adapter.setViewBinder(this);

		setListAdapter(adapter);
	}

	public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
		switch(view.getId()){
		case R.id.itemDate:
			long when = cursor.getLong(columnIndex);
			String date = (String) DateUtils.formatSameDayTime(when, mNow, DateFormat.SHORT, DateFormat.SHORT);
			((TextView) view).setText(date);
			return true;
		}
		return false;
	}

	/**
	 * Carga los datos en segundo plano
	 * 
	 * @author francho
	 * 
	 */
	class MyLoadFeeds extends LoadFeedsAsyncTask {

		public MyLoadFeeds() {
			super(getContentResolver());
		}

		/**
		 * Antes de ejecutar la tarea (tiene acceso al hilo de interface)
		 */
		@Override
		protected void onPreExecute() {
			setProgressBarIndeterminateVisibility(true);
			super.onPreExecute();
		}

		/**
		 * Si se cancela (tiene acceso al hilo de interface)
		 */
		@Override
		protected void onCancelled() {
			setProgressBarIndeterminateVisibility(false);
			super.onCancelled();
		}

		/**
		 * Una vez finalizado (tiene acceso al hilo de interface)
		 */
		@Override
		protected void onPostExecute(Void result) {
			setProgressBarIndeterminateVisibility(false);
			super.onPostExecute(result);
		}

		// Nota: el m�todo doInBackground est� en el padre
	}

}
